package com.hanbang.chu_xing_gao_zhao.view_find_classroom;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.FindClassroomStudyData;
import com.hanbang.chu_xing_gao_zhao.myview.ListViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.chu_xing_gao_zhao.view_public.DynamicCommentActivity;
import com.hanbang.chu_xing_gao_zhao.view_public.VideoPlayActivity;
import com.hanbang.cxgz_2.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * 课堂展示详情与资料详情展示
 */
public class FindClassroomStudyDatailsActivity extends BaseActivity {
    private Intent intent;
    /**
     * 显示过程图片或视频
     */
    private ViewGroup imageParent;
    /**
     * 评论列表
     */
    private ListViewForScrollView listView;
    private ListViewAdapter adapter;

    private ArrayList<FindClassroomStudyData> listData = new ArrayList<FindClassroomStudyData>();


    private PullToRefreshScrollView scrollView;
    /**
     * 请求参数
     */
    private RequestParams params;
    /**
     * 内容的ID
     */
    private int detailsId;
    /**
     * 存放图片与视频的路径
     */
    private String[] dataArray;
    /**
     * 接收接口传过来的对象
     */
    private FindClassroomStudyData data;
    /**
     * 视频的地址
     */
    private String url = "";
    /**
     * 标题
     */
    private TextView title;
    /**
     * 分享
     */
    private ImageView share;
    /**
     * 收藏
     */
    private CheckBox collect;
    /**
     * 销售
     */
    private TextView sale;
    /**
     * 评分
     */
    private TextView grade;
    /**
     * 发表评论
     */
    private TextView comment;
    /**
     * 细节描述
     */
    private TextView descaribe;

    private int pageIndex = 1;
    private int pageSize = 10;
    private String httpUtl;
    /**
     * 接口访问类型
     * 1是：加载视频与图片
     * 2是：加载评论
     * 3是：发表评论
     * 4是：判断是否收藏
     * 5是：收藏
     * 6是：取消收藏
     * 7是：分享
     */
    private int type = 1;

    private String userTlephone;
    private String userPassword;

    private int visitType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_classroom_details);
        initView();
        setOnClickListener();



    }

    /**
     * 初始化view
     */
    private void initView() {
        setTitleMore(View.VISIBLE, View.VISIBLE, "资料详情", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
        userTlephone = MySharedPreferences.getSharedPreferencesKeyAndValue(FindClassroomStudyDatailsActivity.this, MySharedPreferences.USER_DATA, "tlephone");
        userPassword = MySharedPreferences.getSharedPreferencesKeyAndValue(FindClassroomStudyDatailsActivity.this, MySharedPreferences.USER_DATA, "password");

        listData = new ArrayList<FindClassroomStudyData>();
        imageParent = (ViewGroup) findViewById(R.id.ll_find_classroom_details_parent);
        listView = (ListViewForScrollView) findViewById(R.id.lv_find_classroom_details_comment);
        title = (TextView) findViewById(R.id.tv_find_classroom_details_title);
        share = (ImageView) findViewById(R.id.iv_find_classroom_details_share);
        collect = (CheckBox) findViewById(R.id.cb_find_classroom_details_collect);
        sale = (TextView) findViewById(R.id.tv_find_classroom_details_sales);
        grade = (TextView) findViewById(R.id.tv_find_classroom_details_grade);
        comment = (TextView) findViewById(R.id.tv_find_classroom_details_comment);
        descaribe = (TextView) findViewById(R.id.tv_find_classroom_details_descatibe);
        scrollView = (PullToRefreshScrollView) findViewById(R.id.sv_find_classroom_details_scrollView);

        //调用接口
        intent = getIntent();
        detailsId = intent.getIntExtra("id", 1);
        visitType = intent.getIntExtra("visitType", 1);
        httpUtl = intent.getStringExtra("httpUtl");


        //页面的初始显示
        type = 1;
        params = new RequestParams();
        params.addBodyParameter("telphone", userTlephone);
        params.addBodyParameter("password", userPassword);
        params.addBodyParameter("id", detailsId + "");
        getHttpList(httpUtl, params, type);

        //调评论接口
        type = 2;
        RequestParams paramsB = new RequestParams();
        paramsB.addBodyParameter("telphone", userTlephone);
        paramsB.addBodyParameter("password", userPassword);
        paramsB.addBodyParameter("id", detailsId + "");
        paramsB.addBodyParameter("type", visitType + "");
        paramsB.addBodyParameter("pageIndex", pageIndex + "");
        paramsB.addBodyParameter("pageSize", pageSize + "");
        getHttpList(HttpInterfaces.Comment_List, paramsB, type);


        //判断是否收藏
        type = 4;
        RequestParams paramsC = new RequestParams();
        paramsC.addBodyParameter("telphone", userTlephone);
        paramsC.addBodyParameter("password", userPassword);
        paramsC.addBodyParameter("id", detailsId + "");
        paramsC.addBodyParameter("type", visitType + "");
        getHttpList(HttpInterfaces.IfFavorite, paramsC, type);

        //初始化评论列表
        adapter = new ListViewAdapter(listData);
        listView.setAdapter(adapter);


    }

    /**
     * 添加展示图片与视频,其它内容的赋值
     */
    private void addVeiw() {
        //内容赋值
        title.setText(data.getTitle());
        sale.setText("销量：" + data.getBuycount() + "");
        grade.setText("评分：" + data.getPingfen() + "");
        descaribe.setText(data.getRemark());

        //如果是空加载一个默认图片
        if (data.getImgs_url() == null) {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
            imageView.setImageResource(R.drawable.default_white);
            imageParent.addView(imageView);
            return;
        }

        /*
        *1， 如果不是空则显示出来
        *2，根据数组的长度创建ImageView。
        * */
        for (int i = 0; i < dataArray.length; i++) {

            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, 0, 50);
            imageView.setLayoutParams(lp);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setAdjustViewBounds(true);
            imageView.setId(1000 + i);


            /*1.如果是视频则添加点击事件;
            * 2,设置视频默认显示图片
            * 3,得到视频的地址*/
            if (dataArray[i].contains(".mp4")) {
                imageView.setOnClickListener(onClickListener);
                imageView.setImageResource(R.drawable.default_play);
                url = SystemTools.getHttpFileUrl(dataArray[i]);

            } else {
                bitmapUtils.display(imageView, SystemTools.getHttpFileUrl(dataArray[i]));

            }
            imageParent.addView(imageView);
        }


    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        comment.setOnClickListener(onClickListener);
        collect.setOnClickListener(onClickListener);
        share.setOnClickListener(onClickListener);


        //上下刷新的调用
        scrollView.setMode(PullToRefreshBase.Mode.BOTH);
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                pageIndex = 1;
                listData.clear();
                type = 2;
                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userTlephone);
                params.addBodyParameter("password", userPassword);
                params.addBodyParameter("id", detailsId + "");
                params.addBodyParameter("type", visitType + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("pageSize", pageSize + "");
                getHttpList(HttpInterfaces.Comment_List, params, type);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                pageIndex++;
                type = 2;
                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userTlephone);
                params.addBodyParameter("password", userPassword);
                params.addBodyParameter("id", detailsId + "");
                params.addBodyParameter("type", visitType + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("pageSize", pageSize + "");
                getHttpList(HttpInterfaces.Comment_List, params, type);
            }
        });


        /**
         * 分享的回调
         */
        oks.setCallback(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                type = 7;
                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", userTlephone);
                params.addBodyParameter("password", userPassword);
                params.addBodyParameter("feed_id", userData.getId() + "");
                params.addBodyParameter("id", detailsId + "");
                getHttpList(HttpInterfaces.Feed_Share, params, type);

            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });

    }

    /**
     * 处理监听
     */
    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent;
            //判断图片或视频的点击
            for (int i = 0; i < imageParent.getChildCount(); i++) {

                if (v.getId() == imageParent.getChildAt(i).getId()) {
                    intent = new Intent(FindClassroomStudyDatailsActivity.this, VideoPlayActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);

                    return;
                }

            }


            switch (v.getId()) {
                //跳转评论编辑页面
                case R.id.tv_find_classroom_details_comment:
                    intent = new Intent(FindClassroomStudyDatailsActivity.this, DynamicCommentActivity.class);
                    startActivityForResult(intent, 1212);
                    break;
                case R.id.cb_find_classroom_details_collect:
                    if (!collect.isSelected()) {
                        type = 5;
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("telphone", userTlephone);
                        params.addBodyParameter("password", userPassword);
                        params.addBodyParameter("id", detailsId + "");
                        params.addBodyParameter("type", visitType + "");
                        getHttpList(HttpInterfaces.Favorite_Add, params, type);
                    } else {
                        type = 6;
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("telphone", userTlephone);
                        params.addBodyParameter("password", userPassword);
                        params.addBodyParameter("id", detailsId + "");
                        params.addBodyParameter("type", visitType + "");
                        getHttpList(HttpInterfaces.Favorite_Cancel, params, type);
                    }

                    break;

                case R.id.iv_find_classroom_details_share:
                    showShare(getApplicationContext());
                default:
                    break;
            }


        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //得到编辑结果，发表评论
        if (requestCode == 1212 && resultCode == RESULT_OK) {
            type = 3;
            RequestParams params = new RequestParams();
            params = new RequestParams();
            params.addBodyParameter("telphone", userTlephone);
            params.addBodyParameter("password", userPassword);
            params.addBodyParameter("id", detailsId + "");
            params.addBodyParameter("type", visitType + "");
            params.addBodyParameter("text", data.getStringExtra("commentText"));
            getHttpList(HttpInterfaces.Comment_Add, params, type);

//            MyLog.e("text", "0000*****" + data.getStringExtra("commentText"));

        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    /**
     * 获取课堂细节数据
     */
    private void getHttpList(String url, RequestParams params, final int type) {
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    /**
                     * 加载视频与图片的
                     */
                    if (type == 1) {
                        boolean result = json.getBoolean("Result");
                        if (result) {

                            //1.先解析成一个object类型
                            JSONObject dataObject = json.getJSONObject("model");

                            //2.转换成具体对象
                            data = JsonHelper.parseObject(dataObject, FindClassroomStudyData.class);


                            //如果有图片或视频地址分开，并放入数组中
                            if (data.getImgs_url() != null) {

                                dataArray = data.getImgs_url().split(",");
                            }


                            addVeiw();
                        }
                    }
                    //获取列表
                    if (type == 2) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            JSONArray data = json.getJSONArray("list");

                            if (data.length() == 0) {
                                MyToast.show(FindClassroomStudyDatailsActivity.this, "没有更多内容", 1);
                            }
                            listData.addAll(JsonHelper.parseCollection(data, ArrayList.class, FindClassroomStudyData.class));
                            adapter.notifyDataSetChanged();
                            scrollView.onRefreshComplete();
                        }
                    }

                    //发表评论
                    if (type == 3) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            MyToast.show(FindClassroomStudyDatailsActivity.this, "评论成功", 1);

                        }
                    }


                    //判断是否收藏
                    if (type == 4) {
                        boolean result = json.getBoolean("Result");
                        if (result) {
                            boolean IfFavorite = json.getBoolean("IfFavorite");
                            if (IfFavorite) {
                                collect.setSelected(true);
                                ((TextView) findViewById(R.id.tv_find_classroom_details_collect)).setText("已收藏");
                            } else {
                                collect.setSelected(false);
                                ((TextView) findViewById(R.id.tv_find_classroom_details_collect)).setText("收藏");
                            }

                        }
                    }


                    //收藏
                    if (type == 5) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            MyLog.e("text", "已收藏");//*****
                            collect.setSelected(true);
                            ((TextView) findViewById(R.id.tv_find_classroom_details_collect)).setText("已收藏");

                        }
                    }

                    //取消收藏
                    if (type == 6) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            MyLog.e("text", "收藏");//*****
                            collect.setSelected(false);
                            ((TextView) findViewById(R.id.tv_find_classroom_details_collect)).setText("收藏");

                        }
                    }


                    //分享
                    if (type == 7) {
                        int result = json.getInt("Result");
                        if (result == 0) {
                            MyToast.show(FindClassroomStudyDatailsActivity.this, "分享成功", 1);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class ListViewAdapter extends BaseAdapter {

        public ArrayList<FindClassroomStudyData> list = new ArrayList<FindClassroomStudyData>();

        public ListViewAdapter(ArrayList<FindClassroomStudyData> listData) {
            this.list = listData;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public FindClassroomStudyData getItem(int position) {

            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                convertView = getLayoutInflater().inflate(R.layout.item_find_classroom_details, null);
                UiUtils.applyFont(convertView);


                viewHolder = new ViewHolder();
                // 子控件初始化
                viewHolder.portraitId = (ImageView) convertView.findViewById(R.id.iv_tiem_find_classroom_details_portrait);
                viewHolder.name = (TextView) convertView.findViewById(R.id.tv_tiem_find_classroom_details_name);
                viewHolder.comment = (TextView) convertView.findViewById(R.id.tv_tiem_find_classroom_details_comment);
                viewHolder.time = (TextView) convertView.findViewById(R.id.tv_tiem_find_classroom_details_time);


                convertView.setTag(viewHolder);// 把现有有item对象存起来
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            final FindClassroomStudyData data = getItem(position);

            bitmapUtils.display(viewHolder.portraitId, SystemTools.getHttpFileUrl(data.getImg_url()));

            viewHolder.name.setText(data.getTitle());
            viewHolder.comment.setText(data.getText());
            viewHolder.time.setText("评论时间:" + StringUtils_2.getTime(data.getAdd_time()));


            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            // 子控件主要是里面的数据
            private ImageView portraitId;
            private TextView name;
            private TextView comment;
            private TextView time;

        }

    }


}
